<?php

declare(strict_types=1);

namespace App\Server;

use Swlib\Http\ContentType;
use Swlib\SaberGM;
use Swlib\Saber;
use Swlib\Http\Exception\RequestException;

class SaberNetwork
{
    protected $saber;

    
    /**
     * $options array http请求基本参数
     */
    public function __construct($config)
    {
        try {
            if(isset($config['base_uri'])){
                $this->saber = Saber::create([
                    'base_uri' => $config['base_uri'],
                    'timeout' => $config['time_out'] ?? 15,
                    'use_pool' => true
                ]);
                
            }else{
                $this->saber = Saber::create([
                    'use_pool' => true,
                    'timeout' => 15,
                ]);
            }
            
        } catch (RequestException $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * $url string get请求的地址
     */
    public function get($url = '')
    {
        try {
            $content = $this->saber->get($url)->getBody();
            return ['errorCode' => 0, 'data' => (string)$content];
        } catch (RequestException $e) {
            return ['errorCode' => $e->getCode(), 'data' => $e->getMessage()];
        }
    }
    /**
     * $url string post请求的地址
     * $data array post请求的数据
     */
    public function post($url = '', $data = [])
    {
        try {
            $content = $this->saber->post($url, $data)->getBody();
            return ['errorCode' => 0, 'data' => (string)$content];
        } catch (RequestException $e) {
            return ['errorCode' => $e->getCode(), 'data' => $e->getMessage()];
        }
    }

    /** 微信json的post请求
     * $url string post请求的地址
     * $data array post请求的数据
     */
    public function jsonpost($url='',$data=[]){
        try {
            $saber = Saber::create([
                'base_uri' => 'https://www.baidu.com/',
                'headers' => [
                    'Accept-Language' => 'en,zh-CN;q=0.9,zh;q=0.8',
                    'Content-Type' => ContentType::JSON,
                    'DNT' => '1',
                    'User-Agent' => null
                ]
            ]);
            $client = $saber->post($url,$data);
            return $client->getBody()->getContents();
        } catch (RequestException $e) {
            return ['errorCode' => $e->getCode(), 'data' => $e->getMessage()];
        }
    }

}
